package com.example.controller;

import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.utils.JwtUtils;
import com.example.utils.ThreadLocalUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Tag(name = "用户")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result register(@RequestBody @Valid User user) {
        User register = userService.register(user);
        if (register == null) {
            return Result.success("注册成功", userService.save(user));
        }
        return Result.error(500, "用户已存在");
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result login(@RequestBody @Valid User user) {
        User one = userService.login(user);
        if (one == null) {
            return Result.error(500, "用户不存在");
        }
        if (user.getPassword().equals(one.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", one.getId());

            String token = JwtUtils.createToken(claims);
            return Result.success("登录成功", token);
        }
        return Result.error(500, "密码错误");
    }

    @GetMapping("/userInfo")
    @Operation(summary = "用户信息")
    public Result userInfo() {
        Map<String, Object> map = ThreadLocalUtils.get();
        String id = (String) map.get("id");
        User userInfo = userService.getById(id);
        return Result.success("获取用户信息成功", userInfo);
    }
}
